package com.zhsj.OkeHomeConsumption.ui.activity.entering;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.annotation.NonNull;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.OrientationHelper;
import android.support.v7.widget.RecyclerView;
import android.text.InputType;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RadioGroup;


import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.hjq.base.BaseDialog;
import com.hjq.dialog.WaitDialog;
import com.hjq.widget.CountdownView;
import com.zhsj.OkeHomeConsumption.R;
import com.zhsj.OkeHomeConsumption.common.Constants;
import com.zhsj.OkeHomeConsumption.common.MyActivity;
import com.zhsj.OkeHomeConsumption.common.OkeHomeConsumptionApi;
import com.zhsj.OkeHomeConsumption.empty.CityPartneryiyuanBean;
import com.zhsj.OkeHomeConsumption.empty.SelectCityEnity;
import com.zhsj.OkeHomeConsumption.network.HttpClient;
import com.zhsj.OkeHomeConsumption.network.JsonResponseHandler;
import com.zhsj.OkeHomeConsumption.other.TimeOutHandler;
import com.zhsj.OkeHomeConsumption.other.URLEntity;
import com.zhsj.OkeHomeConsumption.ui.activity.WebActivity;
import com.zhsj.OkeHomeConsumption.ui.activity.entering.mvp.EnteringPersonPresenter;
import com.zhsj.OkeHomeConsumption.ui.activity.entering.mvp.EnteringPersonUIInterFace;
import com.zhsj.OkeHomeConsumption.ui.activity.wallet.ClearEditText;
import com.zhsj.OkeHomeConsumption.utils.CodeUtils;
import com.zhsj.OkeHomeConsumption.utils.SelectCityPicker;
import com.zhsj.OkeHomeConsumption.utils.SignUtil;
import com.zhsj.OkeHomeConsumption.utils.StringUtils;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * author : Xingdx
 * <p>
 * time   : 2018/10/18
 * desc   : 申请城市合伙人
 */
public final class CityPartnerActivity extends MyActivity implements EnteringPersonUIInterFace {
    @BindView(R.id.city_recy)
    RecyclerView cityRecy;
    //单位姓名（非必填）
    @BindView(R.id.unit_name)
    ClearEditText unitName;

    //姓名
    @BindView(R.id.name)
    ClearEditText name;

    //城市
    @BindView(R.id.selet_city)
    ClearEditText seletCity;

    //详细地址
    @BindView(R.id.address)
    ClearEditText address;

    //电话
    @BindView(R.id.phone)
    ClearEditText phone;

    //验证码
    @BindView(R.id.verification_code)
    ClearEditText verificationCode;
    @BindView(R.id.btn_test_login)
    Button btnTestLogin;
    @BindView(R.id.cv_register_countdown)
    CountdownView cvRegisterCountdown;
    //关于我们
    @BindView(R.id.guanyuwomen_lin)
    LinearLayout guanyuwomenLin;

    //入驻条件
    @BindView(R.id.tianjian_lin)
    LinearLayout tianjian_lin;


    //入驻理由
    @BindView(R.id.grounds_lin)
    LinearLayout groundsLin;

    //入驻流程
    @BindView(R.id.liucheng_lin)
    LinearLayout liuchengLin;


    private BaseDialog pDialogUtils = null;

    private ShopAdapter shopadper = null;

    private EnteringPersonPresenter minePersonPresenter;

    private List<CityPartneryiyuanBean> mCityPartneryiyuanlist = null;
    private ArrayList<SelectCityEnity> mSelectCityLists = null;

    private ArrayList<String> options1Items = new ArrayList<>();//省
    private ArrayList<ArrayList<String>> options2Items = new ArrayList<>();//市
    private ArrayList<ArrayList<ArrayList<String>>> options3Items = new ArrayList<>();//区

    private int proviceId = -1;//省
    private int mcityId = -1;//市
    private int districCountryId = -1;//区
    private int streetId ;//街道

    @Override
    protected int getLayoutId() {
        return R.layout.entering_activity_citypartner;
    }

    @Override
    protected int getTitleId() {
        return R.id.tb_about_title;
    }

    @Override
    protected void initView() {
        seletCity.setEnabled(true);
        seletCity.setInputType(InputType.TYPE_NULL);
        seletCity.setFocusableInTouchMode(false);
        seletCity.setFocusable(false);
        seletCity.setCursorVisible(false);
        pDialogUtils = new BaseDialog(this);
    }

    @Override
    protected void initData() {
        minePersonPresenter = new EnteringPersonPresenter(getActivity(), this);
        minePersonPresenter.Cooperationwillingness();
        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
        //设置布局管理器
        cityRecy.setLayoutManager(layoutManager);
        //设置为垂直布局，这也是默认的
        layoutManager.setOrientation(OrientationHelper.VERTICAL);
        cityRecy.setNestedScrollingEnabled(false);//禁止滑动
        //设置Adapter
        shopadper = new ShopAdapter();
        cityRecy.setAdapter(shopadper);
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }


    /**
     * 获取意愿信息
     */
    @Override
    public void Cooperationwillingness(String context, int desireType) {
        try {
            JSONTokener jsonT = new JSONTokener(context);
            JSONObject jsonOBJ = (JSONObject) jsonT.nextValue();
            String code = jsonOBJ.optString("code");
            String message = jsonOBJ.optString("message");
            if (code.equals("N000000")) {
                JSONArray jsonarr = jsonOBJ.optJSONArray("data");
                mCityPartneryiyuanlist = new Gson().fromJson(jsonarr.toString(), new
                        TypeToken<ArrayList<CityPartneryiyuanBean>>() {
                        }.getType());
                for (int i = 0; i < mCityPartneryiyuanlist.size(); i++) {
                    mCityPartneryiyuanlist.get(i).setRadio_flage(true);
                }
                shopadper = new ShopAdapter();
                cityRecy.setAdapter(shopadper);
            } else if (code.equals(Constants.STATUSTOKENERROR)) {
                // token过期
                if (!message.equals("null")) {
                    toast(message);
                }
            } else {
                if (!message.equals("null")) {
                    toast(message);
                }
            }
        } catch (JSONException ex) {
            Log.e("UserDetailPost", "获取用户信息异常");
        }
    }

    /**
     * 申请成为城市合伙人
     */
    @Override
    public void CityPsot(String context, String lifeCityCopartnerDTO) {
        try {
            JSONTokener jsonT = new JSONTokener(context);
            JSONObject jsonOBJ = (JSONObject) jsonT.nextValue();
            String code = jsonOBJ.optString("code");
            String message = jsonOBJ.optString("message");
            if (code.equals("N000000")) {
                finish();
            } else if (code.equals(Constants.STATUSTOKENERROR)) {
                // token过期
                if (!message.equals("null")) {
                    toast(message);
                }
            } else {
                if (!message.equals("null")) {
                    toast(message);
                }
            }
        } catch (JSONException ex) {
            Log.e("UserDetailPost", "获取用户信息异常");
        }
    }


    /**
     * 获取城市列表
     */
    @Override
    public void CityListPsot(String context) {
        try {
            JSONTokener jsonT = new JSONTokener(context);
            JSONObject jsonOBJ = (JSONObject) jsonT.nextValue();
            String code = jsonOBJ.optString("code");
            String message = jsonOBJ.optString("message");
            if (code.equals("N000000")) {
                JSONArray jsonarr = jsonOBJ.optJSONArray("data");
                // 数据对接正常
                mSelectCityLists = new Gson().fromJson(jsonarr.toString(), new
                        TypeToken<ArrayList<SelectCityEnity>>() {
                        }.getType());
                getSelectCity(mSelectCityLists);
//                citylist(mSelectCityLists);
            } else if (code.equals(Constants.STATUSTOKENERROR)) {
                // token过期
                if (!message.equals("null")) {
                    toast(message);
                }
            } else {
                if (!message.equals("null")) {
                    toast(message);
                }
            }
        } catch (JSONException ex) {
            Log.e("CityListPsot", "获取城市列表");
        }
    }

    @OnClick({R.id.selet_city, R.id.btn_test_login, R.id.cv_register_countdown,R.id.guanyuwomen_lin,R.id.grounds_lin,R.id.liucheng_lin,R.id.tianjian_lin})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.selet_city:
                //选择城市
                minePersonPresenter.CityListPsot();
                break;
            case R.id.btn_test_login:
                //提交数据
                citypost();
                break;
            case R.id.cv_register_countdown:
                // 发送验证码
                String strPhoneNum = phone.getText().toString().trim();
                if (TextUtils.isEmpty(strPhoneNum)) {
                    toast("请填写手机号");
                    cvRegisterCountdown.resetState();
                    return;
                }
                if (phone.getText().toString().length() != 11) {
                    toast("请输入正确的手机号码");
                    cvRegisterCountdown.resetState();
                    return;
                }
                SendCodevolleyPost(strPhoneNum);
                break;
            case R.id.guanyuwomen_lin:
                Intent intent = new Intent(getActivity(), WebActivity.class).putExtra("url",OkeHomeConsumptionApi.ELVDOU_BASEURL_H5_LIFE + "app/h5/platform/2.html");
                startActivity(intent);
                break;
            case R.id.grounds_lin:
                Intent intent2 = new Intent(getActivity(), WebActivity.class).putExtra("url",OkeHomeConsumptionApi.ELVDOU_BASEURL_H5_LIFE + "app/h5/platform/10.html");
                startActivity(intent2);
                break;
            case R.id.liucheng_lin:
                Intent intent3 = new Intent(getActivity(), WebActivity.class).putExtra("url",OkeHomeConsumptionApi.ELVDOU_BASEURL_H5_LIFE + "app/h5/platform/9.html");
                startActivity(intent3);
                break;
            case R.id.tianjian_lin:
                Intent intent4 = new Intent(getActivity(), WebActivity.class).putExtra("url",OkeHomeConsumptionApi.ELVDOU_BASEURL_H5_LIFE + "app/h5/platform/3.html");
                startActivity(intent4);
                break;

        }
    }

    private void citypost() {
        String unitNamestr = unitName.getText().toString().trim();
        String namestr = name.getText().toString().trim();
        if (StringUtils.isEmpty(namestr)) {
            toast("请输入正确的姓名");
            return;
        }
        String seletCitystr = seletCity.getText().toString().trim();
        if (StringUtils.isEmpty(seletCitystr)) {
            toast("请选择城市");
            return;
        }
        String addressstr = address.getText().toString().trim();
        if (StringUtils.isEmpty(addressstr)) {
            toast("请填写详细地址");
            return;
        }

        String strPhoneNum = phone.getText().toString().trim();
        if (TextUtils.isEmpty(strPhoneNum)) {
            toast("请填写手机号");
            return;
        }
        String verification = verificationCode.getText().toString().trim();
        if (TextUtils.isEmpty(verification)) {
            toast("请填写验证码");
            return;
        }
        List<Map<Object, Object>> yiyuanlist = new ArrayList<>();
        for (int i = 0; i < mCityPartneryiyuanlist.size(); i++) {
            Map<Object, Object> map = new HashMap<>();
            map.put("desireId", mCityPartneryiyuanlist.get(i).getId());
            if (mCityPartneryiyuanlist.get(i).isRadio_flage()) {
                map.put("status", 0);
            } else {
                map.put("status", 1);
            }
            yiyuanlist.add(map);
        }
        Gson gson = new Gson();
        Map<String, Object> mapjson = new HashMap<>();
        mapjson.put("companyName", unitNamestr);
        mapjson.put("userName", namestr);
        mapjson.put("provinceId", proviceId);//省id
        mapjson.put("cityId", mcityId);//市ID
        mapjson.put("districCountryId", districCountryId);//县ID
        mapjson.put("streetId", streetId);//街道id
        mapjson.put("address", addressstr);
        mapjson.put("mobile", strPhoneNum);
        mapjson.put("verifyCode", verification);
        mapjson.put("lifeDesireRelaList", yiyuanlist);//意愿关系
        String lifeCityCopartnerDTO = gson.toJson(mapjson);//map转json字符串
        minePersonPresenter.CityPsot(lifeCityCopartnerDTO);
    }

    public class ShopAdapter extends BaseQuickAdapter<CityPartneryiyuanBean, BaseViewHolder> {
        public ShopAdapter() {
            super(R.layout.item_citypartner_yiyuan, mCityPartneryiyuanlist);
        }

        @Override
        protected void convert(@NonNull BaseViewHolder helper, final CityPartneryiyuanBean item) {
            helper.setText(R.id.title_text, item.getContent());
            RadioGroup radio = helper.itemView.findViewById(R.id.radio);
            radio.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(RadioGroup group, int checkedId) {
                    switch (checkedId) {
                        case R.id.radio1:
                            item.setRadio_flage(true);
                            break;
                        case R.id.radio2:
                            item.setRadio_flage(false);
                            break;
                    }

                }
            });

        }
    }

    /**
     * 选择城市
     *
     * @param mSelectProviceEnities
     */
    private void getSelectCity(ArrayList<SelectCityEnity> mSelectProviceEnities) {
        SelectCityPicker selectCityPicker = new SelectCityPicker(getActivity(), mSelectProviceEnities);
        selectCityPicker.setHalfScreen(true);
        selectCityPicker.setCancelTextColor(R.color.colorAccent);
        selectCityPicker.setSubmitTextColor(R.color.colorAccent);
        selectCityPicker.setOnCitySelectListener(new SelectCityPicker.OnCitySelectListener() {
            @Override
            public void onCitySelect(String province, String city, String county, String town, int provinceId, int cityId, int countyId, int townId) {
                if (!province.equals("") && city.equals("") && county.equals("") && town.equals("")) {
                    seletCity.setText(province);
                } else if (!province.equals("") && !city.equals("") && !county.equals("") && town.equals("")) {
                    seletCity.setText(province + "-" + city + "-" + county);
                } else if (!province.equals("") && !city.equals("") && county.equals("") && town.equals("")) {
                    seletCity.setText(province + "-" + city);
                } else {
                    seletCity.setText(province + "-" + city + "-" + county + "-" + town);
                }
                proviceId = provinceId;
                mcityId =  cityId;
                districCountryId = countyId;
                streetId = townId;
            }
        });
        selectCityPicker.show();
    }






    /**
     * @Title: SendCodevolleyPost @Description: TODO 获取验证码异步线程 @param @param
     * strPhoneNum 输入的手机号 @return void 返回类型 @throws
     */
    public void SendCodevolleyPost(String strPhoneNum) {
        // TODO Auto-generated method stub
        // post传参使用的HashMap
        HashMap<String, String> paramMaps = new HashMap<String, String>();
        // 生成sign值所使用的HashMap
        HashMap<String, String> mSendCodeHashMap = new HashMap<String, String>();
        // mParamHashMap.put("token", Constants.TOKEN);
        mSendCodeHashMap.put("v", Constants.APPVERSION);
        mSendCodeHashMap.put("t", Constants.TIME);
        mSendCodeHashMap.put("deviceId", URLEntity.getInstance().getImei());
        mSendCodeHashMap.put("platform", Constants.PLAFORM);
        String phoneString = CodeUtils.encryptAES(strPhoneNum, CodeUtils.password);
        mSendCodeHashMap.put("mobile", phoneString);
        mSendCodeHashMap.put("client", Constants.CLIENT);
        paramMaps.put("mobile", phoneString);
        // 网络计时器及线程

        // 获取sign签名
        Constants.SIGN = SignUtil.getInstance().getSign(mSendCodeHashMap);
        HttpClient.post(OkeHomeConsumptionApi.ELVDOU_SMSCODE, paramMaps, new JsonResponseHandler() {

            @Override
            public void onSuccess(int statusCode, String content) {
                // TODO Auto-generated method stub
                super.onSuccess(statusCode, content);
                try {
                    JSONTokener jsonT = new JSONTokener(content);
                    JSONObject jsonOBJ = (JSONObject) jsonT.nextValue();
                    String code = jsonOBJ.optString("code");
                    if (code.equals("N000000")) {
                        // 数据对接正常
                        toast("验证码已发送");
                    } else {
                        cvRegisterCountdown.resetState();
                        toast("验证码发送失败");
                    }
                } catch (Exception ex) {
                    log(ex.toString());
                }

            }

            @Override
            public void onFailure(Throwable e) {
                super.onFailure(e);
                pDialogUtils.dismiss();
                TimeOutHandler.pDialogUtils = null;
            }
        });

    }


}
